<template>
  <div class="write-page">
    <NavBar />
    
    <div class="main-content">
      <div class="container">
            <div class="write-header">
              <h1 class="page-title">写文章</h1>
              <div class="header-actions">
                <!-- 自动保存状态提示 -->
                <div class="auto-save-status" v-if="hasUnsavedChanges || isAutoSaving">
                  <el-icon v-if="isAutoSaving" class="is-loading"><Loading /></el-icon>
                  <span v-if="isAutoSaving">自动保存中...</span>
                  <span v-else-if="hasUnsavedChanges" class="unsaved">有未保存的更改</span>
                </div>
                
                <el-button @click="saveDraft" :loading="saving" size="small">
                  <el-icon><Document /></el-icon>
                  保存草稿
                </el-button>
                <el-button type="primary" @click="publishPost" :loading="publishing" size="small">
                  <el-icon><Upload /></el-icon>
                  发布文章
                </el-button>
              </div>
            </div>
        
        
        <div class="write-form">
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="80px"
            class="post-form"
          >
            <el-form-item label="标题" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入文章标题"
                size="large"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
            
            <el-form-item label="内容" prop="content" class="content-editor">
              <MarkdownEditor v-model="form.content" />
            </el-form-item>
            
            <el-form-item label="分类" prop="category_id">
              <el-select
                v-model="form.category_id"
                placeholder="选择分类"
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="标签" prop="tag_ids">
              <TagSelector
                v-model="form.tag_ids"
                :available-tags="availableTags"
                @tag-created="onTagCreated"
              />
            </el-form-item>
            
            <el-form-item>
              <div class="form-options">
                <el-checkbox v-model="form.is_featured">设为精选</el-checkbox>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    
    <!-- 悬浮操作按钮 -->
    <div class="floating-actions">
      <el-button 
        @click="saveDraft" 
        :loading="saving"
        class="floating-btn draft-btn"
      >
        <el-icon><Document /></el-icon>
        保存草稿
      </el-button>
      <el-button 
        type="primary" 
        @click="publishPost" 
        :loading="publishing"
        class="floating-btn publish-btn"
      >
        <el-icon><Upload /></el-icon>
        发布文章
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { usePostsStore } from '@/stores/posts'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import NavBar from '@/components/NavBar.vue'
import MarkdownEditor from '@/components/MarkdownEditor.vue'
import TagSelector from '@/components/TagSelector.vue'
import api from '@/utils/api'
import type { PostCreate } from '@/types'

const router = useRouter()
const postsStore = usePostsStore()
const userStore = useUserStore()

const formRef = ref<FormInstance>()
const saving = ref(false)
const publishing = ref(false)
const generating = ref(false)

// 自动保存相关
const autoSaveTimer = ref<number | null>(null)
const lastSavedContent = ref('')
const hasUnsavedChanges = ref(false)
const isAutoSaving = ref(false)
const currentDraftId = ref<number | null>(null)

const form = reactive({
  title: '',
  content: '',
  excerpt: '',
  cover_image: '',
  is_published: false,
  is_featured: false,
  category_id: null as number | null,
  tag_ids: [] as number[]
})

// 标签验证逻辑已经移到TagSelector组件中

const rules: FormRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 5, max: 200, message: '标题长度在5到200个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    { min: 10, message: '文章内容不能少于10个字符', trigger: 'blur' }
  ],
  excerpt: [
    { max: 500, message: '摘要长度不能超过500个字符', trigger: 'blur' }
  ]
}

// 分类和标签数据
const categories = ref<any[]>([])
const tags = ref<any[]>([])
const suggestedTags = ref<any[]>([])
const availableTags = ref<any[]>([])


// 方法

// 标签处理函数已经移到TagSelector组件中

// 处理新标签创建
const onTagCreated = (newTag: any) => {
  // 将新标签添加到可用标签列表中
  availableTags.value.push(newTag)
}

// 生成封面图片URL
const generateCoverImage = async () => {
  try {
    generating.value = true
    console.log('开始生成封面图片...')
    
    // 调用后端API生成图片URL
    const response = await api.post('/posts/generate-cover-image')
    form.cover_image = response.data.url
    
    console.log('封面图片生成成功:', response.data.url)
  } catch (error) {
    console.error('生成封面图片失败:', error)
    // 如果生成失败，使用默认图片
    form.cover_image = 'https://picsum.photos/800/400'
  } finally {
    generating.value = false
  }
}

// 自动保存相关函数
const startAutoSave = () => {
  // 清除之前的定时器
  if (autoSaveTimer.value) {
    clearInterval(autoSaveTimer.value)
  }
  
  // 每10秒检查一次是否有变化
  autoSaveTimer.value = setInterval(() => {
    if (hasUnsavedChanges.value && !saving.value && !publishing.value) {
      autoSaveDraft()
    }
  }, 10000)
}

const stopAutoSave = () => {
  if (autoSaveTimer.value) {
    clearInterval(autoSaveTimer.value)
    autoSaveTimer.value = null
  }
}

const autoSaveDraft = async () => {
  if (!form.title.trim() && !form.content.trim()) {
    return // 没有内容时不保存
  }
  
  try {
    isAutoSaving.value = true
    
    const draftData = {
      title: form.title.trim(),
      content: form.content.trim(),
      excerpt: form.excerpt || '',
      cover_image: form.cover_image || '',
      is_published: false,
      is_featured: form.is_featured || false,
      category_id: form.category_id || null,
      tag_ids: form.tag_ids && form.tag_ids.length > 0 ? form.tag_ids : null
    }
    
    let response
    if (!currentDraftId.value) {
      // 没有草稿ID，创建新草稿
      response = await api.post('/posts/create', draftData)
      currentDraftId.value = response.data.id
      console.log('创建草稿成功，ID:', currentDraftId.value)
    } else {
      // 有草稿ID，更新现有草稿
      response = await api.put(`/posts/${currentDraftId.value}`, draftData)
      console.log('更新草稿成功，ID:', currentDraftId.value)
    }
    
    // 更新最后保存的内容
    lastSavedContent.value = JSON.stringify(draftData)
    hasUnsavedChanges.value = false
    
    console.log('自动保存草稿成功')
  } catch (error) {
    console.error('自动保存草稿失败:', error)
  } finally {
    isAutoSaving.value = false
  }
}

// 监控内容变化
const checkForChanges = () => {
  const currentContent = JSON.stringify({
    title: form.title.trim(),
    content: form.content.trim(),
    excerpt: form.excerpt || '',
    cover_image: form.cover_image || '',
    is_featured: form.is_featured || false,
    category_id: form.category_id || null,
    tag_ids: form.tag_ids && form.tag_ids.length > 0 ? form.tag_ids : null
  })
  
  hasUnsavedChanges.value = currentContent !== lastSavedContent.value
}

// 监听表单数据变化
watch([() => form.title, () => form.content, () => form.excerpt, () => form.cover_image, () => form.is_featured, () => form.category_id, () => form.tag_ids], () => {
  checkForChanges()
}, { deep: true })

// 获取标签名称
const getTagName = (tagId: number | string | null) => {
  if (tagId === null || tagId === undefined) {
    return '未知标签'
  }
  
  let id: number
  if (typeof tagId === 'string') {
    id = parseInt(tagId)
    if (isNaN(id)) {
      console.warn('无效的标签ID:', tagId)
      return `标签${tagId}`
    }
  } else {
    id = Number(tagId)
    if (isNaN(id)) {
      console.warn('无效的标签ID:', tagId)
      return `标签${tagId}`
    }
  }
  
  const tag = availableTags.value.find(t => t && t.id === id)
  if (!tag) {
    console.warn('标签未找到:', { tagId, id, availableTags: availableTags.value })
    return `标签${id}`
  }
  return tag.name || `标签${id}`
}

// 获取标签颜色
const getTagColor = (tagId: number | string) => {
  let id: number
  if (typeof tagId === 'string') {
    id = parseInt(tagId)
    if (isNaN(id)) {
      return '#409EFF'
    }
  } else {
    id = tagId
  }
  
  const tag = availableTags.value.find(t => t.id === id)
  return tag ? tag.color : '#409EFF'
}

const loadCategories = async () => {
  try {
    const response = await api.get('/posts/categories')
    console.log('分类API响应:', response.data)
    
    if (Array.isArray(response.data)) {
      categories.value = response.data
    } else {
      console.warn('分类数据格式不正确:', response.data)
      categories.value = []
    }
  } catch (error) {
    console.error('加载分类失败:', error)
    // 如果API失败，使用默认分类
    categories.value = [
      { id: 1, name: '技术' },
      { id: 2, name: '生活' },
      { id: 3, name: '随笔' }
    ]
  }
}

const loadTags = async () => {
  try {
    const response = await api.get('/posts/tags')
    console.log('标签API响应:', response.data)
    
    // 确保响应数据是数组
    if (Array.isArray(response.data)) {
      // 确保每个标签对象都有正确的结构
      const validTags = response.data.filter(tag => tag && typeof tag.id === 'number' && typeof tag.name === 'string')
      tags.value = validTags
      suggestedTags.value = validTags.slice(0, 5)
      availableTags.value = validTags
      console.log('标签加载成功:', { validTags, suggestedTags: suggestedTags.value, availableTags: availableTags.value })
    } else {
      console.warn('标签数据格式不正确:', response.data)
      tags.value = []
      suggestedTags.value = []
      availableTags.value = []
    }
  } catch (error) {
    console.error('加载标签失败:', error)
    // 如果API失败，使用默认标签
    const defaultTags = [
      { id: 1, name: 'Vue', color: '#4fc08d' },
      { id: 2, name: 'JavaScript', color: '#f7df1e' },
      { id: 3, name: 'Python', color: '#3776ab' },
      { id: 4, name: 'FastAPI', color: '#009688' }
    ]
    tags.value = defaultTags
    suggestedTags.value = defaultTags.slice(0, 5)
    availableTags.value = defaultTags
    console.log('使用默认标签:', { defaultTags, suggestedTags: suggestedTags.value, availableTags: availableTags.value })
  }
}

// 添加标签到选择列表
const addTag = (tagId: number) => {
  if (!form.tag_ids.includes(tagId)) {
    form.tag_ids.push(tagId)
  }
}

// 删除标签（从已选择列表中移除）
const removeTag = (tagId: number) => {
  const index = form.tag_ids.indexOf(tagId)
  if (index > -1) {
    form.tag_ids.splice(index, 1)
  }
}

// 删除标签（从系统中删除）
const deleteTagFromSystem = async (tagId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个标签吗？这将从系统中永久删除此标签。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 调用删除标签API
    await api.delete(`/posts/tags/${tagId}`)
    
    // 从本地列表中移除
    const index = suggestedTags.value.findIndex(tag => tag.id === tagId)
    if (index > -1) {
      suggestedTags.value.splice(index, 1)
    }
    
    // 从可用标签中移除
    const availableIndex = availableTags.value.findIndex(tag => tag.id === tagId)
    if (availableIndex > -1) {
      availableTags.value.splice(availableIndex, 1)
    }
    
    // 从已选择的标签中移除
    const selectedIndex = form.tag_ids.indexOf(tagId)
    if (selectedIndex > -1) {
      form.tag_ids.splice(selectedIndex, 1)
    }
    
    ElMessage.success('标签删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除标签失败:', error)
      ElMessage.error('删除标签失败')
    }
  }
}

const generateContent = async () => {
  ElMessage.info('摘要和封面将在发布时自动生成')
}

const saveDraft = async () => {
  if (!formRef.value) return
  
  try {
    // 草稿保存时，只验证必填字段，不进行完整验证
    if (!form.title.trim()) {
      ElMessage.error('请输入文章标题')
      return
    }
    
    if (!form.content.trim()) {
      ElMessage.error('请输入文章内容')
      return
    }
    
    saving.value = true
    
    // 确保数据格式正确
    const draftData = {
      title: form.title.trim(),
      content: form.content.trim(),
      excerpt: form.excerpt || '',
      cover_image: form.cover_image || '',
      is_published: false,
      is_featured: form.is_featured || false,
      category_id: form.category_id || null,
      tag_ids: form.tag_ids && form.tag_ids.length > 0 ? form.tag_ids : null
    }
    
    console.log('保存草稿数据:', draftData)
    
    let response
    if (!currentDraftId.value) {
      // 没有草稿ID，创建新草稿
      response = await api.post('/posts/create', draftData)
      currentDraftId.value = response.data.id
      console.log('创建草稿成功，ID:', currentDraftId.value)
    } else {
      // 有草稿ID，更新现有草稿
      response = await api.put(`/posts/${currentDraftId.value}`, draftData)
      console.log('更新草稿成功，ID:', currentDraftId.value)
    }
    
    ElMessage.success('草稿保存成功')
  } catch (error) {
    console.error('保存草稿失败:', error)
    ElMessage.error('保存草稿失败，请重试')
  } finally {
    saving.value = false
  }
}

const publishPost = async () => {
  if (!formRef.value) return
  
  try {
    // 发布文章时，进行基本验证
    if (!form.title.trim()) {
      ElMessage.error('请输入文章标题')
      return
    }
    
    if (!form.content.trim()) {
      ElMessage.error('请输入文章内容')
      return
    }
    
    if (form.title.trim().length < 5) {
      ElMessage.error('标题长度不能少于5个字符')
      return
    }
    
    if (form.content.trim().length < 10) {
      ElMessage.error('文章内容不能少于10个字符')
      return
    }
    
    publishing.value = true
    
    // 发布时自动生成摘要和封面
    let publishData = {
      title: form.title.trim(),
      content: form.content.trim(),
      excerpt: form.excerpt || '',
      cover_image: form.cover_image || '',
      is_published: true,
      is_featured: form.is_featured || false,
      category_id: form.category_id || undefined,
      tag_ids: form.tag_ids && form.tag_ids.length > 0 ? form.tag_ids : undefined
    }
    
    // 后端会自动生成摘要和封面，前端不需要处理
    
    console.log('发布文章数据:', publishData)
    
    // 显示处理中的提示
    const loadingMessage = ElMessage({
      message: '正在处理图片并发布文章，请稍候...',
      type: 'info',
      duration: 0 // 不自动关闭
    })
    
    if (currentDraftId.value) {
      // 有草稿ID，更新现有草稿为发布状态
      await api.put(`/posts/${currentDraftId.value}`, publishData)
      console.log('发布草稿成功，ID:', currentDraftId.value)
    } else {
      // 没有草稿ID，创建新文章
      await postsStore.createPost(publishData)
    }
    
    // 发布成功后，刷新文章列表以更新草稿箱
    await postsStore.fetchPosts({ published_only: false })
    
    loadingMessage.close()
    ElMessage.success('文章发布成功')
    router.push('/posts')
  } catch (error) {
    console.error('发布文章失败:', error)
    
    // 根据错误类型显示不同的提示
    if ((error as any).code === 'ECONNABORTED') {
      ElMessage.error('请求超时，图片处理时间较长，请重试')
    } else if ((error as any).response?.status === 500) {
      ElMessage.error('服务器处理图片时出错，请重试')
    } else {
      ElMessage.error('发布文章失败，请重试')
    }
  } finally {
    publishing.value = false
  }
}

onMounted(async () => {
  // 检查是否有token（从localStorage检查，因为store可能还没初始化）
  const hasToken = userStore.token || localStorage.getItem('token')
  if (!hasToken) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  // 确保用户信息已加载
  if (!userStore.user) {
    try {
      await userStore.fetchUserInfo()
    } catch (error) {
      console.error('获取用户信息失败:', error)
      ElMessage.error('获取用户信息失败，请重新登录')
      userStore.logout()
      router.push('/login')
      return
    }
  }

  // 加载分类和标签数据
  await loadCategories()
  await loadTags()
  
  // 立即生成封面图片URL
  await generateCoverImage()
  
  // 启动自动保存
  startAutoSave()
})

onUnmounted(() => {
  // 组件销毁时停止自动保存
  stopAutoSave()
})
</script>

<style scoped>
.write-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding: 2rem 0;
  background: #f5f7fa;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 60px;
}

.write-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 1.5rem;
  font-weight: 700;
  color: #333;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.auto-save-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.875rem;
  color: #666;
  margin-right: 12px;
}

.auto-save-status .unsaved {
  color: #f56c6c;
}

.auto-save-status .is-loading {
  color: #409eff;
}

.write-form {
  background: white;
  border-radius: 8px;
  padding: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-height: 70vh;
}

.post-form {
  max-width: none;
}

.form-options {
  display: flex;
  gap: 2rem;
}

/* 调试信息样式 */
.debug-info {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 2rem;
  font-family: 'Courier New', monospace;
}

.debug-info h3 {
  margin: 0 0 1rem 0;
  color: #495057;
  font-size: 1rem;
}

.debug-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.debug-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.25rem 0;
  border-bottom: 1px solid #e9ecef;
}

.debug-item strong {
  color: #495057;
  font-size: 0.875rem;
}

.debug-item span.success {
  color: #28a745;
  font-weight: bold;
}

.debug-item span.error {
  color: #dc3545;
  font-weight: bold;
}

.debug-actions {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

@media (max-width: 768px) {
  .write-header {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .write-form {
    padding: 1rem;
  }
  
  .form-options {
    flex-direction: column;
    gap: 1rem;
  }
  
  .debug-grid {
    grid-template-columns: 1fr;
  }
  
  .debug-actions {
    justify-content: center;
  }
}

.form-item-with-action {
  display: flex;
  gap: 8px;
  align-items: flex-start;
}

.generate-btn {
  margin-top: 4px;
  white-space: nowrap;
}

.cover-preview {
  margin-top: 8px;
}

.cover-image {
  max-width: 200px;
  max-height: 120px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.tag-selector {
  width: 100%;
}

.selected-tags {
  margin-top: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.selected-tags-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.selected-tag {
  margin: 0;
  transition: all 0.2s ease;
  background: transparent !important;
  border: 2px solid #409eff !important;
  color: #333 !important;
  font-weight: 500;
}

.selected-tag:hover {
  transform: scale(1.05);
  border-color: #337ecc !important;
  background: #f0f9ff !important;
}

.tag-suggestions {
  margin-top: 12px;
  padding: 12px;
  background: #f0f9ff;
  border-radius: 6px;
  border: 1px solid #e0f2fe;
}

.suggestion-label {
  font-size: 12px;
  color: #0369a1;
  margin-bottom: 8px;
  font-weight: 500;
}

.suggestion-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.suggestion-tag {
  cursor: pointer;
  transition: all 0.2s ease;
  margin: 0;
  background: transparent !important;
  border: 1px solid #d0d7de !important;
  color: #333 !important;
  font-weight: 500;
}

.suggestion-tag:hover {
  transform: scale(1.05);
  border-color: #409eff !important;
  background: #f0f9ff !important;
  color: #409eff !important;
}

.content-editor {
  width: 100%;
  margin-bottom: 2rem;
}

.content-editor :deep(.el-form-item__content) {
  width: 100%;
}

.content-editor :deep(.markdown-editor) {
  width: 100%;
}

/* 悬浮操作按钮 */
.floating-actions {
  position: fixed;
  bottom: 20px;
  right: 20px;
  display: flex;
  gap: 12px;
  z-index: 1000;
}

.floating-btn {
  height: 48px;
  padding: 0 20px;
  border-radius: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  font-weight: 500;
  transition: all 0.3s ease;
}

.floating-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.draft-btn {
  background: white;
  border: 1px solid #dcdfe6;
  color: #606266;
}

.draft-btn:hover {
  background: #f5f7fa;
  border-color: #409eff;
  color: #409eff;
}

.publish-btn {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  border: none;
  color: white;
}

.publish-btn:hover {
  background: linear-gradient(135deg, #337ecc 0%, #529b2e 100%);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .floating-actions {
    bottom: 10px;
    right: 10px;
    flex-direction: column;
    gap: 8px;
  }
  
  .floating-btn {
    height: 44px;
    padding: 0 16px;
    font-size: 14px;
  }
}
</style>
